package com.sy.simpleegg.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.bumptech.glide.Glide
import com.sy.simpleegg.R
import com.sy.simpleegg.databinding.DialogSaveCoinBinding
import com.sy.simpleegg.ext.countDown
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.onClick
import com.sy.simpleegg.util.QRCodeUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel


class SaveCoinDialog(
    private val title: String?,
    private val tips: String?,
    private val codeData: String?,
    private val countDownTime: Int,
    private var saveCoinDialogListener: SaveCoinDialogListener,
): DialogFragment() {

    private lateinit var binding: DialogSaveCoinBinding

    var timeDownScope: CoroutineScope? = null

    private var transId = ""
    private var userId = ""
    private var orderNumber = ""
    private var currentSaveCoins = "0"

    private var countDownDismiss = false

    override fun onStart() {
        super.onStart()
//        dialog!!.window!!.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        val width = resources.getDimensionPixelSize(R.dimen.dialog_withdrawal_width)
        val height = resources.getDimensionPixelSize(R.dimen.dialog_withdrawal_height)
//        val marginBottom = resources.getDimensionPixelSize(R.dimen.dialog_good_detail_margin_bottom)

//        dialog!!.window!!.setLayout(width, height + marginBottom)
        dialog!!.window!!.setLayout(width, height)
        dialog!!.window!!.setGravity(Gravity.CENTER)
        dialog!!.setCanceledOnTouchOutside(false)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        binding = DialogSaveCoinBinding.inflate(inflater, container, false)
//        setStyle(STYLE_NO_TITLE, R.style.MyDialog)
//        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT))
//        dialog!!.window!!.setGravity(Gravity.BOTTOM)
        dialog!!.window!!.setBackgroundDrawableResource(R.color.transparent)
//        var wlp = dialog!!.window!!.attributes
//        wlp.gravity = Gravity.BOTTOM
//        wlp.width = WindowManager.LayoutParams.MATCH_PARENT
//        wlp.height = WindowManager.LayoutParams.MATCH_PARENT
//        dialog!!.window!!.attributes = wlp

        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        try {
            binding.tvTitle.text = title
            binding.tvTips.text = tips

            binding.layoutClose.tvDismiss.text = "${countDownTime}S"

            binding.layoutClose.tvClose.onClick {
//                saveCoinDialogListener.back()
//                dismissAllowingStateLoss()
                saveCoin()
            }
            binding.btnBack.onClick {
//                saveCoinDialogListener.back()
//                dismissAllowingStateLoss()
                saveCoin()
            }

            codeData?.let {
                refreshQrCode(it, "")
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("初始化页面异常：${e.message}")
        }
    }

    override fun showNow(manager: FragmentManager, tag: String?) {
        super.showNow(manager, tag)
        startCountDown(countDownTime)
    }

    override fun show(manager: FragmentManager, tag: String?) {
        super.show(manager, tag)
        startCountDown(countDownTime)
    }

    override fun show(transaction: FragmentTransaction, tag: String?): Int {
        val result = super.show(transaction, tag)
        startCountDown(countDownTime)
        return result

    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        saveCoinDialogListener.dismiss()
    }

    private fun saveCoin(){
        binding.btnBack.isClickable = false
        binding.layoutClose.tvClose.isClickable = false

        timeDownScope?.cancel()
        saveCoinDialogListener.saveCoins(orderNumber, userId, transId, currentSaveCoins)
    }

    /**
     * 刷新二维码
     * @param qrCode 二维码数据
     */
    fun refreshQrCode(qrCode: String, transId: String){
        try {
            if (qrCode.isEmpty()){
                binding.pbQrCode.visibility = View.VISIBLE
                binding.ivQrCode.visibility = View.GONE
                return
            }
            this.transId = transId
            binding.pbQrCode.visibility = View.GONE
            Glide.with(binding.root)
                .load(QRCodeUtil.createQRCode(qrCode, 500, 500))
                .fitCenter()
                .into(binding.ivQrCode)
            binding.ivQrCode.visibility = View.VISIBLE
            startCountDown(countDownTime)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新二维码异常：${e.message}")
        }
    }

    /**
     * 用户登录成功
     */
    fun login(orderNumber: String, uid: String){
        try {
            userId = uid
            this.orderNumber = orderNumber
            binding.llSaveInfo.visibility = View.VISIBLE
            binding.tvSaveCoin.text = currentSaveCoins
            binding.flScanCode.visibility = View.GONE
            startCountDown(countDownTime)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("会员存币登录 处理异常：${e.message}")
        }
    }

    fun getOrderNumber(): String{
        return orderNumber
    }

    /**
     * 刷新存币数据
     * @param coins 存币数
     */
    fun refreshSaveCoins(coins: String){
        try {
            currentSaveCoins = coins
            binding.tvSaveCoin.text = coins
            startCountDown(countDownTime)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新存币数异常：${e.message}")
        }
    }

    /**
     * 关闭窗口
     */
    fun dismissNow(){
        dismissAllowingStateLoss()
    }

    fun saveFinish(){
        try {
            binding.tvResult.text = requireContext().getString(R.string.member_save_coins_finish)
            countDownDismiss = true
            startCountDown(5)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新存币数异常：${e.message}")
        }
    }

    @SuppressLint("SetTextI18n")
    private fun startCountDown(timeout: Int){
//        var timeDownScope: CoroutineScope? = null
        timeDownScope?.cancel()

        countDown(
            time = timeout,
            start = {
                timeDownScope = it
                logFile("开始倒计时")
            },
            end = {
                logFile("结束倒计时")
            },
            next = {
                binding.layoutClose.tvDismiss.text = "${it}S"
                if (it == 0){
                    if (countDownDismiss){
                        dismissAllowingStateLoss()
                    }else{

                        binding.btnBack.isClickable = false
                        binding.layoutClose.tvClose.isClickable = false
                        saveCoinDialogListener.saveCoins(orderNumber, userId, transId, currentSaveCoins)
                    }
                }
            })
    }

    interface SaveCoinDialogListener{
        fun dismiss()

        fun back()

        fun saveCoins(orderNumber: String, userId: String, transId: String, coins: String)
    }

    fun dpToPx(context: Context, dp: Int): Int {
        val density = context.resources.displayMetrics.density
        return Math.round(dp * density)
    }
}